//
//  OAuthViewController.swift
//  sinaweibowj
//
//  Created by Macintosh on 15/12/15.
//  Copyright © 2015年 mactoinsh. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    
    
    override func loadView() {
        view = webView
        //设置代理
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        print(view.classForCoder)
        //加载授权页面
        loadOAuthPage()
        //设置导航条
        setNavBar()
    }
    
    //加载授权页面
    func loadOAuthPage(){
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        
        webView.loadRequest(NSURLRequest(URL: url!))
    }
    
    //设置导航条
    func setNavBar(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭" , style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        
    }
    
    @objc private func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func defaultAccount(){
        //ME
                let  jsString = "document.getElementById('userId').value = '18865384936',document.getElementById('passwd').value = 'wangjuan521.' "
        //谢晨
//        let jsString = "document.getElementById('userId').value = '18235760514' ,document.getElementById('passwd').value = 'xch19900721.' "
        //刘陈红
        //        let jsString = "document.getElementById('userId').value = '18865384821' ,document.getElementById('passwd').value = '12345678'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
}


//是相关的代码更加模块化，易于维护
extension OAuthViewController:UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //需要根据请求的URL，去屏蔽不希望加载的页面
        //print(request.URL?.absoluteString)
        guard let urlString = request.URL?.absoluteString else{
            return false
        }
        if urlString.hasPrefix("https://api.weibo.com/") {
            //希望加载的页面
            return true
        }
        if !urlString.hasPrefix("http://www.baidu.com") {
            //一定不是请求成功后的回调 同样 也不会是我们想要加载的页面
            return false
        }
        
        //程序走到这里一定是成功后的回调
        print(urlString)
        //解析字符串获取code码
        //quary 获取url中 键值
        if let q = request.URL?.query {
            //字符串截取操作
            let codeStr = "code="
            let code = q.substringFromIndex(codeStr.endIndex)
            //print(code)
            //加载用户的token
            loadAccessToken(code)
        }
        
        
        return false
    }
    
    //加载用户token（请求标识）
    private func loadAccessToken(code :String ){
        
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            if isSuccess {
                print("登录成功")
                //动画结束发出页面切换的通知
                //通知是同步的
                //self.close()
                
                //这个方法时控制器dismiss掉，但是并不会立即被回收
                self.dismissViewControllerAnimated(false , completion: { () -> Void in
                    //等待被model的页面 彻底被回收 在发出页面切换的通知
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "welcome")
                    print("come here")
                })
                
            }else {
                
                print("登录失败")
            }
            
        }
        
    }
    
}


